package com.zx.gateway.util

import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono

/**
 * webflux forward util
 */
object WebfluxForwardingUtil {
    /**
     *
     * @param exchange: the current source server exchange
     * @param forwardAttrs : the attributes that added to forward Exchange.
     * @return Mono<Void> to signal forwarding request completed.
    </Void> */
    fun forward(exchange: ServerWebExchange, forwardAttrs: Map<String?, Any?>?): Mono<Void> {
        val webFilterChain = exchange.attributes["filterchain"] as WebFilterChain?
        val forwardReq = exchange.request.mutate().build()
        val forwardExchange = exchange.mutate().request(forwardReq).build()
        if (!forwardAttrs.isNullOrEmpty()) {
            forwardExchange.attributes.putAll(forwardAttrs)
        }
        return webFilterChain!!.filter(forwardExchange)
    }
}
